package com.lanyou.esb.redis;

import java.io.IOException;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Service;

import redis.clients.jedis.Jedis;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.lanyou.cook.common.Constants;
import com.lanyou.cook.entity.domain.ParamSetting;
import com.lanyou.cook.paramsetting.ParamSettingReppository;
import com.lanyou.esb.exception.ParamSetRuntimeException;
import com.lanyou.esb.redis.vo.RedisSetting;

/**
 * 初始化REDIS服务器参数配置
 * 
 * @author Davey.wu
 */
@Service
public class RedisContextInit implements
		ApplicationListener<ContextRefreshedEvent> {
	@Autowired
	private ParamSettingReppository paramSettingReppository;

	@Override
	public void onApplicationEvent(ContextRefreshedEvent event) {
		// 获取参数
		ParamSetting paramSettingServer = paramSettingReppository
				.findByParamName(Constants.REDIS_SERVER);
		ObjectMapper mapper = new ObjectMapper();
		RedisSetting redisSetting = null;
		try {
			// 将JSON转换成REDIS参数配置对象
			redisSetting = mapper.readValue(paramSettingServer.getParamValue(),
					RedisSetting.class);
			// 设置REDIS服务器配置参数
			JedisPoolUtils.setRedisSetting(redisSetting);

			// 测试连接
			testConnect();
		} catch (IOException e) {
			String msg = "ERROR:连接不上redis服务器，请确认参数设置是否正确【value="
					+ paramSettingServer.getParamValue() + "】";
			throw new ParamSetRuntimeException(msg, "");
		}
	}

	/**
	 * 测试连接JEDIS服务器
	 * 
	 * @throws JsonProcessingException
	 */
	private void testConnect() throws JsonProcessingException {
		Jedis jedis = null;
		boolean broken = false;
		try {
			jedis = JedisPoolUtils.getJedis();
			if (jedis == null) {
				RedisSetting setting = JedisPoolUtils.getRedisSetting();
				String msg = "ERROR:连接不上redis服务器，请确认参数设置是否正确";
				if (setting != null) {
					ObjectMapper mapper = new ObjectMapper();
					String json = mapper.writeValueAsString(setting);
					msg += "【value=" + json + "】";
				}
				throw new ParamSetRuntimeException(msg, "");
			}
		} catch (Exception e) {
			broken = true;
			RedisSetting setting = JedisPoolUtils.getRedisSetting();
			String msg = "ERROR:连接不上redis服务器，请确认参数设置是否正确";
			if (setting != null) {
				ObjectMapper mapper = new ObjectMapper();
				String json = mapper.writeValueAsString(setting);
				msg += "【value=" + json + "】";
			}
			throw new ParamSetRuntimeException(msg, "");
		} finally {
			JedisPoolUtils.returnRes(jedis, broken);
		}
	}

}
